<?php
/*
* the model to deal the menu info
*/

namespace app\admin\model;

use think\facade\Cache;

class Menu extends \app\common\model\Base
{
	protected $table = 'admin_menu';
	protected $_AllowPreprocess=true;
	protected $_AllowRecache=true;

	use \app\common\model\TreeBase;

	public function setRulesAttr($value) {
		if (is_array($value))
			return implode(',',$value);
		else
			return $value;
	}

	public function getRulesAttr($value) {
		if ($value) {
			$val=explode(',',$value);
			foreach ($val as &$v)
				$v=intval($v);
			return $val;
		} else
			return null;
	}

	protected function _before_createData(&$param) {
		if ($param['pid']==0 && !in_array(0,$GLOBALS['userInfo']['gids'])){
			return "只有超级管理员有权限创建根菜单";
		}

		if (isset($param['rules'])){
			$v=&$param['rules'];
			if (is_array($v)) {
				$v=implode(',',$v);
			}
			if ($s=strripos($v,',')){
				$param['rule_id']=intval(substr($v,$s+1));
			} else {
				$param['rule_id']=intval($v);
			}
		}
		return true;
	}

	protected function _before_updateDataById(&$param) {
		if ($param['pid']==0 && !in_array(0,$GLOBALS['userInfo']['gids'])){
			return "只有超级管理员有权限修改根菜单";
		}
		if (isset($param['rules'])){
			$v=&$param['rules'];
			if (is_array($v)){
				$v=implode(',',$v);
			}
			if ($s=strripos($v,',')){
				$param['rule_id']=intval(substr($v,$s+1));
			} else {
				$param['rule_id']=intval($v);
			}
		}
		return true;
	}

	protected function recache() {
		\think\facade\Cache::clear('USER_MENU');
	}

	/*
	* invoke this function will return the menu for the specific user.
	* this function require the userinfo, which store in the cache.
	*/
	public function getUserMenu($userInfo){
		if (null===$userInfo||null===$userInfo['gidkeys'])
			return null;
		$cache = cache('USER_MENU_'.$userInfo['gidkeys']);
		if (!$cache) {
			$map['status']=1;
			if (!in_array(0,$userInfo['gids'])) {
				$groupModel=model('Group');
				$map['rule_id'] = $groupModel->getRulesList_raw($userInfo['gidkeys'],$userInfo['gids']);
			}
			$ids = db('admin_menu')->where($map)->column('id');
			$ids = array_unique(array_merge($this->getAllParent($ids,'pid',[$userInfo['site_id'], 0]),$ids));
			$cache['list'] = db('admin_menu')->where('id','in',$ids)->order('sort_order')->field(['id','title','name','module_name','pid','remark'])->select();
			$cache['tree'] = $this->makeTree($cache['list']);
			if (!cache('USER_MENU_'.$userInfo['gidkeys'],$cache,config('cache_param.menu_expire'),'USER_MENU')) {
				\think\facade\Log::record('缓存用户菜单失败');
			}
		}
		return $cache;
	}
}